let commentform = document.querySelector('.comment-form')
let lessonid = localStorage.getItem('lessonid')
let lessonpage = localStorage.getItem('lessonpage')

function huancun() {

    localStorage.setItem('commentname', commentform.children[1].children[1].value);
    localStorage.setItem('commentscore', commentform.children[2].children[1].value);
    localStorage.setItem('commentthoughts', commentform.children[3].children[1].value);
    localStorage.setItem('commentterm', commentform.children[4].children[1].value);
}

function sendcomment(target) {
    let XHR = new XMLHttpRequest();
    let FD = new FormData(target);
    XHR.addEventListener('load', function (event) {
        obj = JSON.parse(event.target.responseText);
        clearInterval(huancun);
        localStorage.removeItem('commentname');
        localStorage.removeItem('commentscore');
        localStorage.removeItem('commentthoughts');
        localStorage.removeItem('commentterm');
        window.location.href = lessonpage;
    });
    XHR.addEventListener('error', function (event) {
        alert("提交失败，请检查网络连接并重载本页面");
    });
    XHR.open('POST', '/handlecomment/' + lessonid + '/');
    XHR.send(FD);
}
if (localStorage.getItem('commentname') != null) {
    commentform.children[1].children[1].value = localStorage.getItem('commentname');
}
if (localStorage.getItem('commentscore') != null) {
}
commentform.children[2].children[1].value = localStorage.getItem('commentscore');
if (localStorage.getItem('commentthoughts') != null) {
    commentform.children[3].children[1].value = localStorage.getItem('commentthoughts');
}
if (localStorage.getItem('commentterm') != null) {
    commentform.children[4].children[1].value = localStorage.getItem('commentterm');
}

setInterval(huancun, 500);
commentform.addEventListener('submit', function (event) {
    event.preventDefault();
    localStorage.setItem('commentname', event.target.children[1].children[1].value);
    localStorage.setItem('commentscore', event.target.children[2].children[1].value);
    localStorage.setItem('commentthoughts', event.target.children[3].children[1].value);
    localStorage.setItem('commentterm', event.target.children[4].children[1].value);
    sendcomment(event.target);
});